﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevelopTool.Bll.SchedulerBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.CommonForms;
using DevelopTool.Model;
using DevelopTool.Model.SchedulerModels;
using Sunny.UI;

namespace DevelopTool.Forms.SchedulerForms
{
    /// <summary>
    /// 定时任务
    /// </summary>
    public partial class SchedulerForm : BaseUIPage
    {

        /// <summary>
        /// 定时任务操作类
        /// </summary>
        private SchedulerBll schedulerBll;

        /// <summary>
        /// 定时任务-日志操作类
        /// </summary>
        private SchedulerLogBll schedulerLogBll;

        /// <summary>
        /// 定时任务对象
        /// </summary>
        private Scheduler scheduler;


        /// <summary>
        /// 任务详情窗体对象
        /// </summary>
        BaseUIPage schedulerInfoForm = null;


        /// <summary>
        /// DataGridView列信息集合
        /// </summary>
        private readonly List<DataGridColumn> dataGridColumns = new List<DataGridColumn>()
              {
                { new DataGridColumn("CreateTime"){ColumnText="时间",Width=150,ValueFormat="yyyy-MM-dd HH:mm:ss"}},
                { new DataGridColumn("Result"){ColumnText="结果",Width=0,ColumnType = ColumnType.DefaultFilter}},
                { new DataGridColumn("Exception"){ColumnText="异常",Width=0,ColumnType = ColumnType.DefaultFilter}},

                { new DataGridColumn("SchedulerId"){ColumnText="SchedulerId",ColumnType = ColumnType.Hide}},
                { new DataGridColumn("Id"){ColumnText="Id",ColumnType = ColumnType.Hide}},
                { new DataGridColumn("Remark"){ColumnText="Remark",ColumnType = ColumnType.Hide}},
                { new DataGridColumn("UpdateTime"){ColumnText="UpdateTime",ColumnType = ColumnType.Hide}},
              };


        public SchedulerForm(Scheduler scheduler)
        {
            InitializeComponent();

            this.scheduler = scheduler;
            schedulerBll = new SchedulerBll();
            schedulerLogBll = new SchedulerLogBll();
        }

        private void SchedulerForm_Load(object sender,EventArgs e)
        {
            this.txtSchedulerCron.Text = scheduler.Cron;
            this.datetimePickerStart.Text = scheduler.StratTime == null ? "" : scheduler.StratTime.ToDate().ToString(this.datetimePickerStart.DateFormat);
            this.datetimePickerEnd.Text = scheduler.EndTime == null ? "" : scheduler.EndTime.ToDate().ToString(this.datetimePickerEnd.DateFormat);

            this.datetimePickerLogStart.Value = DateTime.MinValue;
            this.datetimePickerLogStart.Text = "";

            this.datetimePickerLogEnd.Value = DateTime.MinValue;
            this.datetimePickerLogEnd.Text = "";


            if(scheduler.SchedulerType == "Sql")
            {
                schedulerInfoForm = new SchedulerForm_Sql(this.scheduler);
            }
            else if(scheduler.SchedulerType == "代码")
            {
                schedulerInfoForm = new SchedulerForm_Code(this.scheduler);
            }

            if(schedulerInfoForm != null)
                TabControlHelper.AddFormToControl(this.tabPage_Info,schedulerInfoForm);

            SetBtnTextByRunState();

            ShowLog();
        }




        /// <summary>
        /// 根据运行状态设置按钮文本和图标
        /// </summary>
        private void SetBtnTextByRunState()
        {
            if(this.schedulerBll.IsRun(this.scheduler))
            {
                this.btnRun.Symbol = 61517;
                this.btnRun.Text = "停止";
            }
            else
            {
                this.btnRun.Symbol = 61515;
                this.btnRun.Text = "运行";
            }
        }

        /// <summary>
        /// cron表达式文本框按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSchedulerCron_ButtonClick(object sender,EventArgs e)
        {
            QuartzCronForm quartzCronForm = new QuartzCronForm(this.txtSchedulerCron.Text);
            if(quartzCronForm.ShowDialog() == DialogResult.OK)
            {
                this.txtSchedulerCron.Text = quartzCronForm.CronText;
            }
        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender,EventArgs e)
        {
            Save();
        }


        private void Save()
        {
            if(string.IsNullOrEmpty(this.txtSchedulerCron.Text))
            {
                this.ShowWarningNotifier("请填写提醒规则Cron");
                return;
            }

            if(schedulerInfoForm.Call())
            {
                this.scheduler.Cron = this.txtSchedulerCron.Text;
                this.scheduler.StratTime = this.datetimePickerStart.Text.ToDateOrNull();
                this.scheduler.EndTime = this.datetimePickerEnd.Text.ToDateOrNull();

                this.scheduler = schedulerBll.Save(this.scheduler);
                this.ShowSuccessNotifier("保存成功");

                //如果保存时任务正在运行，那么就重新启动下任务
                if(this.schedulerBll.IsRun(this.scheduler))
                {
                    schedulerBll.SchedulerRun(this.scheduler);
                }
            }
        }


        /// <summary>
        /// 运行/停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRun_Click(object sender,EventArgs e)
        {
            if(this.schedulerBll.IsRun(this.scheduler))//停止
            {
                var tuple = schedulerBll.SchedulerStop(this.scheduler);
                if(tuple.Item1)
                {
                    this.ShowSuccessNotifier(tuple.Item2);

                    scheduler.IsRun = false;//设置任务状态为停止运行
                    Save();
                }
                else
                {
                    this.ShowWarningNotifier(tuple.Item2);
                }
            }
            else//运行
            {
                var tuple = schedulerBll.SchedulerRun(this.scheduler);
                if(tuple.Item1)
                {
                    this.ShowSuccessNotifier(tuple.Item2);

                    scheduler.IsRun = true;//设置任务状态为正在运行
                    Save();
                }
                else
                {
                    this.ShowWarningNotifier(tuple.Item2);
                }
            }

            SetBtnTextByRunState();
        }


        /// <summary>
        /// 查询日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender,EventArgs e)
        {

            DateTime startTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            if(!string.IsNullOrEmpty(this.datetimePickerLogStart.Text))
            {
                startTime = this.datetimePickerLogStart.Value;
            }

            if(!string.IsNullOrEmpty(this.datetimePickerLogEnd.Text))
            {
                endTime = this.datetimePickerLogEnd.Value;
            }
            ShowLog(startTime,endTime);
        }


        /// <summary>
        /// 展示日志
        /// </summary>
        private void ShowLog(DateTime? startTime = null,DateTime? endTime = null)
        {

            var list = schedulerLogBll.GetList(this.scheduler.Id);//从数据库中查询日志

            if(startTime != null && startTime != DateTime.MinValue)
            {
                list = list.Where(it => it.CreateTime >= startTime).ToList();
            }
            if(endTime != null && endTime != DateTime.MinValue)
            {
                list = list.Where(it => it.CreateTime <= endTime).ToList();
            }

            if(list.Count <= 0)
            {
                list.Add(new SchedulerLog() { CreateTime = DateTime.MinValue });
            }

            this.dataDisplayControl.BindData(list.ToDataTable("SchedulerLog"),this.dataGridColumns,"CreateTime DESC");
        }

    }
}
